//
//  AppDelegate.m
//  Showing
//
//  Created by Ralf on 3/4/15.
//  Copyright (c) 2015 next-software. All rights reserved.
//

#import "AppDelegate.h"
#import "iModern-Swift.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import "UMessage.h"
//#import "UMCommunity.h"
#import "MobClick.h"
#import "JsBridgeModel.h"

#define UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define _IPHONE80_ 80000

@implementation AppDelegate

@synthesize parameterManager;
@synthesize contactManager;

- (void)onlineConfigCallBack:(NSNotification *)note
{

    NSLog(@"online config has fininshed and note = %@", note.userInfo);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    [MobClick setLogEnabled:YES];
    [MobClick setAppVersion:XcodeAppVersion];
    [MobClick startWithAppkey:@"51b326b456240be76300b67a" reportPolicy:(ReportPolicy) REALTIME channelId:nil];
    [MobClick updateOnlineConfig];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onlineConfigCallBack:) name:UMOnlineConfigDidFinishedNotification object:nil];

    [UMessage startWithAppkey:@"51b326b456240be76300b67a" launchOptions:launchOptions];

    [UMSocialData setAppKey:@"51b326b456240be76300b67a"];
    [UMSocialData openLog:YES];

    [UMSocialWechatHandler setWXAppId:@"wx9e6a43ee3974c9de" appSecret:@"e2f003b8d6042916e3904afeb6965517" url:@"https://itunes.apple.com/us/app/ai-mo-deng/id659867594?l=zh&ls=1&mt=8"];
    [UMSocialQQHandler setQQWithAppId:@"1104703317" appKey:@"pSoLMp7t9n2fwNR0" url:@"https://itunes.apple.com/us/app/ai-mo-deng/id659867594?l=zh&ls=1&mt=8"];
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];

    [UMSocialQQHandler setSupportWebView:NO];
    
    //有赞微商城数据加载
//    NSString* secretAgent = [[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
//    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%@%@%@",secretAgent,@"xxxxxxx",@"1.0.1"], @"UserAgent", nil];
//    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
    //有赞微商城数据加载
    
    //友盟微社区
//    [UMCommunity setWithAppKey:@"55fa91e3e0f55ae59a002bca"];
    //友盟微社区

    self.parameterManager = [ParameterManager new];
    self.contactManager   = [ContactManager new];

    if ([self isLogged])
    {
        ResultSet *rs = [self.contactManager loadContact];

        if (rs == nil || rs.hasErrors)
        {
            self.parameterManager.sessionID = @"";
            self.contactManager.contact     = nil;
            [self.parameterManager save];
        }
    }

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    self.rootController                                 = [ConsumerTabBarController new];
    self.navigationController                           = [[UINavigationController alloc] initWithRootViewController:self.rootController];
    self.navigationController.navigationBar.translucent = NO;
    self.rootController.tabBar.translucent              = NO;
    self.window.rootViewController                      = self.navigationController;

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if (UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {

        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier     = @"action1_identifier";
        action1.title          = @"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序

        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier             = @"action2_identifier";
        action2.title                  = @"Reject";
        action2.activationMode         = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive            = YES;

        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1, action2] forContext:(UIUserNotificationActionContextDefault)];

        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];

    }
    else
    {
        //register remoteNotification types

        //                [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
        //                 |UIRemoteNotificationTypeSound
        //                 |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif

    //for log
    [UMessage setLogEnabled:YES];
    [UMessage setBadgeClear:NO];
    [UMessage setChannel:@"App Store"];


    //    //添加tag
    //    [UMessage addTag:@"推送tag"response:^(id responseObject, NSInteger remain, NSError *error) {
    //        }];
    //    //绑定别名(alias)
    //    [UMessage addAlias:@"推送alias" type:kUMessageAliasTypeSina response:^(id responseObject, NSError *error) {
    //        }];
    
    //微社区通知
    /*
    NSDictionary *notificationDict = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if ([notificationDict valueForKey:@"umwsq"]) {
        [UMComMessageManager startWithOptions:launchOptions];
        if ([notificationDict valueForKey:@"aps"]) // 点击推送进入
        {
            [UMComMessageManager didReceiveRemoteNotification:notificationDict];
        }
    } else {
        [UMComMessageManager startWithOptions:nil];
        //使用你的消息通知处理
    }
     */

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [UMessage registerDeviceToken:deviceToken];
    //微社区
//    [UMComMessageManager registerDeviceToken:deviceToken];
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"devicetoken is ：%@", token);
    [ParameterManager SetDeviceToken:token];
    return;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
//    if ([userInfo valueForKey:@"umwsq"]) {
//        [UMComMessageManager didReceiveRemoteNotification:userInfo];
//    }
//    else{
        [UMessage setAutoAlert:NO];
        [UMessage didReceiveRemoteNotification:userInfo];
//    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"Register Remote Notifications error:{%@}", error);

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [UMSocialSnsService handleOpenURL:url];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [UMSocialSnsService applicationDidBecomeActive];
}

- (BOOL)isLogged
{
    return self.parameterManager.sessionID != nil && self.parameterManager.sessionID.length > 0;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
}

@end